require 'rexml/document'
require 'encoder'
require 'channel'
require 'logger'


module PCLink 
  
  class Node 
    attr_reader :name, :nodeid, :url
    def initialize(name, nodeid, url, el)
      @name = name
      @nodeid = nodeid
      @url = url
      @attributes = {}
      el.elements.each do |e| 
        name = e.name
        value = e.text
        @attributes[name] = value
      end
      
    end
    
    def method_missing(name, *args) 
      name = name.to_s
      @attributes[name.to_s] if @attributes.has_key?(name)
    end
      
    def to_s
      "[#{@name} #{@nodeid}]"
    end
  end 
  
  class Track < Node 
    attr_reader :name, :nodeid, :url
    def initialize(name, nodeid, url)
      @url = url
    end
  end 
  
  
  class Server
    attr_reader :name, :port, :ip
    
    def initialize(xml)
      doc = REXML::Document.new(xml)
      doc.root.elements.each do |child|
        instance_variable_set("@"+child.name.downcase, child.text)
      end
      enc = Encoder.new 
      @port = enc.decode_short(@port.to_i) if @port
      @ip = enc.decode_ip(@ip.to_i) if @ip
      @log = Logger.new(STDOUT)
    end
  end
  
  def list_nodes(nodeid = 0)
    @log.info "listing node #{nodeid}"
    @channel = Channel.new(@ip, @port) if !@channel 
    content_data = @channel.list_node(nodeid)
    puts "processing #{content_data.length} nodes"
    nodes = []
    content_data.each do |el|
      nodes << create_node(el)
    end
    nodes 
  end
  
  def channel=(channel)
    @channel = channel
  end
  
  def to_s
    "#{@shortname} - #{@ip}:#{@port}"
  end 
  
  private 
  def create_node(el)
    name = nodeid = url =  nil
    el.elements.each("name") {|e| name = e.text.to_s.chomp}
    el.elements.each("nodeid") {|e| nodeid = e.text.to_i}
    el.elements.each("url") {|e| url = e.text}
    Node.new(name, nodeid, url, el)
  end 
  
end